<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="30%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="departmentForm"
      :model="fromData"
      label-width="100px"
      :rules="rules"
    >
      <el-form-item
        label="部门名称:"
        prop="DepName"
      >
        <el-input
          v-model="fromData.DepName"
          :disabled="!fromDataQX.DepName"
        />
      </el-form-item>
      <el-form-item
        label="部门代号:"
        prop="DepShortName"
      >
        <el-input
          v-model="fromData.DepShortName"
          :disabled="!fromDataQX.DepShortName"
        />
      </el-form-item>
      <el-form-item
        label="部门排序:"
        prop="DepCode"
      >
        <el-input
          v-model="fromData.DepCode"
          type="number"
          :disabled="!fromDataQX.DepCode"
        />
      </el-form-item>
      <el-form-item
        label="部门类型:"
        style="text-align: left !important;"
      >
        <el-radio-group
          v-model="fromData.IsTrue"
          :disabled="!fromDataQX.IsTrue"
        >
          <el-radio :label="'0'">
            实体部门
          </el-radio>
          <el-radio :label="'1'">
            非实体部门
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="handleClose">取 消</el-button>
      <el-button
        type="primary"
        @click="saveDepartment"
      >保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import{BatchTableOperateRequestByCRUD} from '@/api/Hr/index.js'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    departmentData: {
      type: Object,
      default: () => ({}) 
    },
    pdepartmentData: {
      type: Object,
      default: () => ({}) 
    }
  },
  data() {
    return {
      fromData: this.getInitialData(),
      fromDataQX:{
         DepName: true,
         DepShortName: true,
         DepCode: true,
         IsTrue: true
      },
       rules: {
        DepName: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
        ],
        DepCode: [
          { required: true, message: '部门排序不能为空', trigger: 'blur' }, // el-input-number 的触发器通常是 change
        ],        
      }
    }
  },
  watch: {
    departmentData: {
      handler(newVal) {
        // 当父组件传入的 departmentData 变化时，更新表单数据
        if (newVal && Object.keys(newVal).length > 0) {
          console.log(newVal)
          Object.keys(this.fromDataQX).forEach(key => {
  this.fromDataQX[key] = newVal.lingma_sys_params.e.includes(key);
});
        this.fromData = JSON.parse(JSON.stringify(newVal));
        } else {
          // 如果是新增操作，重置表单
          this.resetForm();
        }
      },
      immediate: true,
      deep: true
    },
    dialogVisible(newVal) {
    if (newVal) {
      // 对话框打开时，如果有编辑数据就设置表单
      if (this.departmentData && Object.keys(this.departmentData).length > 0) {
        this.fromData = JSON.parse(JSON.stringify(this.departmentData));
      }
    } else {
      // 对话框关闭时重置表单
      this.$nextTick(() => {
        this.resetForm();
      });
    }
  }
  },
  methods: {
    // 获取初始表单数据
    getInitialData() {
      return {
        DepName: '',
        DepShortName: '',
        DepCode: '',
        IsTrue: '0' // 默认选择实体部门
      };
    },
    
    // 重置表单
    resetForm() {
      this.fromData = this.getInitialData();
      // 如果有表单验证，也清除验证
      if (this.$refs.departmentForm) {
        this.$refs.departmentForm.clearValidate();
      }
    },
    
  
    
    saveDepartment() {
      this.$refs.departmentForm.validate((valid) => {
     if(valid){
          const data = [{
          TableName:'task_demo@Base_DepartInfo',
          CrudModel:{}
     }]
      if(this.title==='新增部门'){
      this.$set(this.fromData, 'createuser', JSON.parse(sessionStorage.getItem('users')).userInfo.ROWID)
    data[0].CrudModel={
        Added:[
            {
            DepName:this.fromData.DepName,
            DepShortName: this.fromData.DepShortName,
            DepCode: this.fromData.DepCode,
            IsTrue: this.fromData.IsTrue,
            DepType:'F',
            DepID:Math.random().toString(36).substring(2) + Date.now().toString(36),
            LepDepID:'',
            LepDepName:'',
            zwSCR:this.pdepartmentData.zwSCR+ '/' +this.fromData.DepName,
            prowid:this.pdepartmentData.DepID,
            DepLevelCode:parseInt(this.pdepartmentData.DepLevelCode)+1,
            DepLevel:this.pdepartmentData.DepLevelCode,
            createuser:this.fromData.createuser
          }

          ],
          Changed:[],
          Deleted:[]
        }
    }else{
       const segments = this.fromData.zwSCR.split('/');
         segments[segments.length - 1] = this.fromData.DepName;
         const zwSCR = segments.join('/');
            this.$set(this.fromData, 'zwSCR', zwSCR)
      data[0].CrudModel={
        Added:[],
        Changed:[
          {
            rowid:this.fromData.rowid,
            DepName:this.fromData.DepName,  
            DepShortName: this.fromData.DepShortName,
            DepCode: this.fromData.DepCode,
            IsTrue: this.fromData.IsTrue,
            zwSCR:zwSCR
          }
        ],
        Deleted:[]
      }
    }
BatchTableOperateRequestByCRUD(data,'DA242D6EF89B69A7ED5D2728408833AB').then(r => {
          if(r.success){
            this.$message.success('保存成功');
            this.$emit('refresh', {
          type: this.title === '新增部门' ? 'add' : 'edit',
          data: this.fromData,
          parentData: this.pdepartmentData
        });
            this.$emit('close');
            this.resetForm();
          }else{
            this.$message.error('保存失败'+r.Message);
     }
    })
  }
})
},
    handleClose() {
  
      this.$emit('close');
      this.resetForm();
    }
  }
};
</script>
<style scoped>
/* 对话框标题左对齐 */
::v-deep .el-dialog__header {
  text-align: left;
}
</style>